import asyncio
from pymodbus.client import ModbusSerialClient
from pymodbus.exceptions import ModbusException

# 配置串口参数
SERIAL_PORT = "COM2"  # Windows系统下的串口设备，Linux系统可能是/dev/ttyUSB0等
BAUDRATE = 9600
UNIT_ID = 1  # Modbus从站的设备地址

async def run_client():
    client = ModbusSerialClient(
        port=SERIAL_PORT,
        baudrate=BAUDRATE,
        timeout=1
    )

    try:
        # 连接到从站
        if client.connect():
            print("Connected to Modbus RTU server")

            # 读取保持寄存器
            address = 0  # 寄存器地址
            count = 1    # 读取数量
            try:
                response = client.read_holding_registers(address=address, count=count, slave=UNIT_ID)
                if response.isError():
                    print(f"Error reading holding registers: {response}")
                else:
                    print(f"Holding register value (address {address}):", response.registers[0])
            except ModbusException as e:
                print("Exception while reading holding registers:", e)

            # # 写入保持寄存器
            # new_value = 0x5678  # 新的寄存器值
            # try:
            #     response = client.write_register(address=address, value=new_value, slave=UNIT_ID)
            #     if response.isError():
            #         print(f"Error writing holding register: {response}")
            #     else:
            #         print(f"Holding register at address {address} set to {new_value}")
            # except ModbusException as e:
            #     print("Exception while writing holding register:", e)

            # # 再次读取保持寄存器，验证写入是否成功
            # try:
            #     response = client.read_holding_registers(address=address, count=count, slave=UNIT_ID)
            #     if response.isError():
            #         print(f"Error reading holding registers after write: {response}")
            #     else:
            #         print(f"Holding register value (address {address}) after write:", response.registers[0])
            # except ModbusException as e:
            #     print("Exception while re - reading holding registers:", e)

        else:
            print("Failed to connect to Modbus RTU server")

    except Exception as e:
        print("General error:", e)

    finally:
        # 关闭连接
        client.close()
        print("Modbus connection closed")


if __name__ == "__main__":
    asyncio.run(run_client())